package com.fary.ibmmq;

import com.fary.config.MQConfigProperties;
import com.fary.config.MQConfigProperties.Source;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 开启mq监听
 */
@Slf4j
@Component
public class StartReceiveListener implements SmartInitializingSingleton, ApplicationContextAware {

    @Autowired
    private MQConfigProperties mqConfigProperties;

    private ApplicationContext applicationContext;

    @Override
    public void afterSingletonsInstantiated() {

        for (Source source : mqConfigProperties.getReceiver().getSourceList()) {
            JmsMessageReceiver jmsMessageReceiver = applicationContext.getBean(JmsMessageReceiver.class);
            jmsMessageReceiver.setNodeFlag(source.getNodeFlag());
            try {
                jmsMessageReceiver.init();
                log.info("{}开始启动，接收消息", jmsMessageReceiver.getNodeFlag());
            } catch (Exception e) {
                log.info("{}启动失败", jmsMessageReceiver.getNodeFlag());
                e.printStackTrace();
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
